$(document).ready(function () {
    get_file_info("../javascript/items_list.json",get_goods_item);
    get_items_count()
});
function get_file_info(url,action){
    $.getJSON(url,action);
}
function get_goods_item(goods_list){
    show_goods_list(goods_list);
    add_click_event(goods_list);
}
function show_goods_list(goods_info){
    $("#form").tmpl(goods_info).appendTo("#product_list");
}
function get_cart_local_data(){
    return JSON.parse(localStorage.getItem("cart_list")) || [];
}
function get_items_count() {
    var count = localStorage.getItem("sum_count") || 0;
    $("#sum_count").html(count);
}
function add_click_event(goods_info){
    $(".button").click(function () {
        show_cart_count();
        var shopping_goods =get_cart_local_data();
        var mark_id= this.id;
        updata_local_goods_data(shopping_goods,mark_id ,goods_info);
        get_goods_save_count();
    });
}
function show_cart_count() {
    var count = $("#sum_count").html();
    count++;
    $("#sum_count").html(count);
    localStorage.setItem("sum_count", count);
}

function updata_local_goods_data(shopping_goods,mark_id ,goods_info){
    var index = _.findIndex(shopping_goods, function (item) {
        return mark_id == item.id;
    });
    updata_local_goods_count(index,mark_id,goods_info,shopping_goods);
    save_cart_list(shopping_goods);
}
function updata_local_goods_count(index,mark_id,goods_info,shopping_goods){
    if(index==-1) {
        add_goods_property_count(mark_id,goods_info,shopping_goods )
    }else {
        shopping_goods[index].count++;
    }
    return shopping_goods;
}
function add_goods_property_count(mark_id,goods_info,shopping_goods ){
    var goods_items= _.find(goods_info,function(item){
        return mark_id == item.id;
    });
    goods_items.count=1;
    shopping_goods.push(goods_items);
}
function get_goods_save_count(){
    get_file_info("../javascript/save_id.json",compute_goods_free_count);
}
function compute_goods_free_count(goods_info){
    var shopping_goods=get_cart_local_data();
    get_goods_free_count(shopping_goods,goods_info);
}
function get_goods_free_count(shopping_goods,goods_info){
    _.each(shopping_goods,function (item){
        compute_free_count(goods_info ,item);
    });
    save_cart_list(shopping_goods);
}
function compute_free_count(goods_info ,item){
    item.free_count=0;
    if(goods_info.indexOf(item.id)!=-1 ){
        item.free_count=Math.floor(item.count / 3);
    }
}
function save_cart_list(value){
    localStorage.setItem("cart_list", JSON.stringify(value));
}